﻿using AutoMapper;
using B.S.Filtration.Domain.工单;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.ContactCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ContactCommandHander
{
    public class QueryContactCommandHander:IRequestHandler<QueryContactCommand,APIPaging<List<Contact>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public QueryContactCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<APIPaging<List<Contact>>> Handle(QueryContactCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<Contact>> result = new APIPaging<List<Contact>>();

            var item = await db.Queryable<Contact>().Where(x => x.Del == false).ToListAsync();

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(x => x.ContactId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            result.code = APIResultCode.success;
            result.msg = "查询联系记录成功";
            result.data = item;

            return result;
        }
    }
}
